import socket
import ConfigParser
import thread
import killProcName
import os,stat,sys
import time
import subprocess
import logging
import traceback
import pyodbc

monitor_logging = None

if stat.S_ISDIR(os.stat(sys.path[0])[stat.ST_MODE]):
    prefixdir = sys.path[0]
else:
    prefixdir = os.path.split(sys.path[0])[0]



def Monitor(processname):
    global monitor_logging
    
    global prefixdir
    print prefixdir
    config = ConfigParser.ConfigParser()
    config.read('server.cfg')
    logfile = config.get("Basic","Log")
    socket_port = config.get("Basic","Port")
    dns_str = config.get("Basic","DSN")    
    
    socket_port = int(socket_port)
    
    sleeptime=int(config.get("Monitor","sleeptime"))
    maxtry = int(config.get("Monitor","maxtry"))
    timeout_cnt = 0
    while True:   

        #check the tcp port
        srvaddr = ('127.0.0.1', socket_port)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(50)
        
        #check the database
        conn = pyodbc.connect(dns_str)            
        cursor = conn.cursor()
        conn.close()

        try:
            s.connect(srvaddr)
            monitor_logging.debug("there is no exception")
        except:
            monitor_logging.debug("socket except")
            timeout_cnt = timeout_cnt + 1
            monitor_logging.debug("the timeout_cnt is %d"%(timeout_cnt))
            if timeout_cnt > maxtry:
                monitor_logging.error("kill server")
                killProcName.killProcName(processname)
                monitor_logging.error("start server")       

                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

                zto_path = "%s\\%s.exe"%(prefixdir,processname)
                monitor_logging.debug('the path is %s'%(zto_path))
    
                ipPipe = subprocess.Popen(('%s'%(zto_path), ), stdout=subprocess.PIPE, startupinfo = startupinfo)
                ipStr = ipPipe.stdout.read(10)
                monitor_logging.debug("the output is %s"%(ipStr))
                time.sleep(sleeptime)
                timeout_cnt = 0
                
        s.close()
        time.sleep(sleeptime)
        
def main():
    global monitor_logging    
    logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s  %(levelname)-8s %(message)s',
                    filename="zto_monitor.log",
                    datefmt="%m-%d %H:%M:%S",        
                    filemode='a')

    console=logging.StreamHandler()
    console.setLevel(logging.ERROR)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

    monitor_logging = logging.getLogger('Monitor')

    monitor_logging.debug("this is my monitor zto_server ")
    Monitor("zto-bj")
         
        
if __name__ == '__main__':
    try:
        main()
    except:
        exption_str=traceback.format_exc()
        monitor_logging.error( "Unexpected error:\n %s ",exption_str )
